// 获取数组原型
const arrayProto = Array.prototype
export const arrayMethods = Object.create(arrayProto)

// 以下方法会改变原数组
const methodsToPatch = [
  'push',
  'pop',
  'shift',
  'unshift',
  'splice',
  'sort',
  'reverse'
]

methodsToPatch.forEach(method => {
  const original = arrayProto[method]
  Object.defineProperty(arrayMethods, method, {
    value: function (...args) {
      const result = original.call(this, ...args)

      // 对新增的数据再次进行劫持
      let inserted
      switch(method) {
        case 'push':
        case 'unshift':
          inserted = args
          break;
        case 'splice':
          inserted = args.slice(2)
          break
      }
      if (inserted) this.__ob__.observeArray(inserted)

      this.__ob__.dep.notify() // 数组变化，通知 watcher 进行更新
      return result
    }
  })
})